package com.ruoyi.common.utils.http;
/**
 * @author 赵常飞
 * @date 2022/12/28 17:51
 */

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.project.mahjong.domain.uyil.DeskUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class HttpUtilsBody {


    public static String getToken(String url, HashMap param) {
        Map params = new HashMap(1 << 1);//用于存放request body
        params.put("clientType", DeskUtils.clientType);
        params.put("appKey", DeskUtils.appKey);
        params.put("AppSecret", DeskUtils.AppSecret);
        params.put("AppSecretKey", DeskUtils.AppSecretKey);
        //创建post请求对象
        HttpPost httppost = new HttpPost(url);//档案系统转换地址
        // 获取到httpclient客户端
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            //添加请求头参数
            httppost.addHeader("Content-Type", "application/json");
            // 设置请求的一些配置设置，主要设置请求超时，连接超时等参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000)
                    .build();
            httppost.setConfig(requestConfig);
            //添加参数
            httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8")));
            // 请求结果
            String resultString = "";
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取请求响应结果
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 将响应内容转换为指定编码的字符串
                    resultString = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("获取到的Response content:{" + resultString + "}");
                }
            } else {
                System.out.println("请求失败！");
            }
            JSONObject json = (JSONObject) JSONObject.parse(resultString);
            System.out.println(JSONObject.parseObject(json.get("data").toString()).get("accesstoken"));
            System.out.println(json.get("accesstoken"));
            return JSONObject.parseObject(json.get("data").toString()).get("accesstoken").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static JSONObject getHttpUrl(String url, String token) throws IOException {

        // 创建连接对象
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        // 设置请求方法为 GET
        connection.setRequestMethod("GET");
        if (!token.isEmpty()) {
            connection.addRequestProperty("Authorization", "Bearer " + token);
        }

        // 获取响应结果
        int responseCode = connection.getResponseCode();
        BufferedReader reader = null;
        StringBuilder resultBuilder = new StringBuilder();

        try {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                resultBuilder.append(line);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        System.out.println("Response Code: " + responseCode);
        System.out.println("Result: " + resultBuilder.toString());
        return null;
    }

    public static JSONObject postHttpUrl(String url, String token,Map params) throws IOException {

        HttpPost httppost = new HttpPost(url);//档案系统转换地址
        // 获取到httpclient客户端
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {

            //添加请求头参数
            httppost.addHeader("Content-Type", "application/json");
            // 设置请求的一些配置设置，主要设置请求超时，连接超时等参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000)
                    .build();
            httppost.setConfig(requestConfig);
            httppost.setHeader("Authorization", "Bearer " + token);
            //添加参数
            httppost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8")));
            // 请求结果
            String resultString = "";
            //启动执行请求，并获得返回值
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取请求响应结果
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 将响应内容转换为指定编码的字符串
                    resultString = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("获取到的Response content:{" + resultString + "}");
                }
            } else {
                System.out.println("请求失败！");
            }
            JSONObject json = (JSONObject) JSONObject.parse(resultString);
            System.out.println(JSONObject.parseObject(json.get("data").toString()).get("accesstoken"));
            System.out.println(json.get("accesstoken"));
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


